package com.nativetalk.service.three.book.update;

import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.book.TdNtBookCourse;
import com.nativetalk.bean.book.TdNtBookCourseUpdate;
import com.nativetalk.bean.book.TdNtBookCourseWeek;
import com.nativetalk.bean.book.TdNtBookCourseWeekHis;
import com.nativetalk.bean.course.TsNtCourseInfoDetail;
import com.nativetalk.bean.member.TdNtMemberTuisong;
import com.nativetalk.bean.member.setmeal.TdNtMembSetmealDetail;
import com.nativetalk.bean.reserve.TdNtReserveInsert;
import com.nativetalk.bean.send.TwNtSendHisInsert;
import com.nativetalk.bean.sms.Sms;
import com.nativetalk.common.Constants;
import com.nativetalk.common.ValidationMessages;
import com.nativetalk.common.getui.AndroidReserveStudent;
import com.nativetalk.common.getui.IosReserveStudent;
import com.nativetalk.common.util.CommonUtil;
import com.nativetalk.common.util.MemcachedKey;
import com.nativetalk.common.util.MemcachedUtils;
import com.nativetalk.common.util.SMSUtil;
import com.nativetalk.dao.*;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by lizhun on 16/8/3.
 */
@Service
public class ThreeBookUpdateServiceImpl implements ThreeBookUpdateService {
    private static Logger logger = Logger.getLogger(ThreeBookUpdateServiceImpl.class);
    @Resource
    private TdNtBookCourseDao tdNtBookCourseDao;
    @Resource
    private TdNtMembSetmealDao tdNtMembSetmealDao;
    @Resource
    private TdNtReserveDao tdNtReserveDao;
    @Resource
    private TdNtMemberDao tdNtMemberDao;
    @Resource
    private TwNtSendHisDao twNtSendHisDao;

    @Override
    public synchronized RetInfo updateBook(TdNtBookCourseUpdate tdNtBookCourseUpdate) {
        String logInfo = this.getClass().getName() + ":updateBook:";
        // 类路径+方法名
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            TdNtBookCourse bookCourse = tdNtBookCourseDao.findBookById(tdNtBookCourseUpdate.getBook_cou_id());
            if (bookCourse != null && bookCourse.getState() == 1) {
                if (bookCourse.getFrequency() != tdNtBookCourseUpdate.getWeeks().size()) {
                    retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                    retInfo.setTip("Please choose the time according to the student's learning frequency ");
                    return retInfo;
                }
                /**
                 * 查找套餐 获取套餐剩余时间
                 */
                Map<String, TsNtCourseInfoDetail> tsNtCourseInfoDetailMap = (Map<String, TsNtCourseInfoDetail>) MemcachedUtils.get(MemcachedKey.tsNtCourseInfoDetailMap);
                TsNtCourseInfoDetail tsNtCourseInfoDetail = tsNtCourseInfoDetailMap.get(bookCourse.getCou_id() + "");
                Map<String, Object> map = new HashMap<>();
                map.put("memb_id", bookCourse.getMemb_id());
                map.put("cou_id", tsNtCourseInfoDetail.getCate_id());
                TdNtMembSetmealDetail tdNtMembSetmealDetail = tdNtMembSetmealDao.findTdNtMembSetmealDetailEnd(map);
                int reserve_size = tdNtMembSetmealDetail.getSurplus_time() / 60;
                /**
                 * 判断明天是星期几
                 */
                SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd");
                Date date = new Date();
                int week = CommonUtil.getWeekday(dateFormater.format(date));
                /**
                 * 获取大于当前周的预约及小于的然后合并
                 */
                List<TdNtBookCourseWeek> weeks = new ArrayList<>();
                int size = 0;
                for (Map.Entry<Integer, Integer> entry : tdNtBookCourseUpdate.getWeeks().entrySet()) {
                    weeks.add(size, tdNtBookCourseDao.findBookWeekById(entry.getKey()));
                }
                TdNtBookCourseWeek bookCourseWeek;
                for (int i = 0; i < weeks.size(); i++) {//趟数

                    for (int j = 0; j < weeks.size() - i - 1; j++) {//比较次数
                        if (weeks.get(j).getWeek() > weeks.get(j + 1).getWeek()) {

                            bookCourseWeek = weeks.get(j);

                            weeks.set(j, weeks.get(j + 1));

                            weeks.set(j + 1, bookCourseWeek);

                        }

                    }

                }
                List<TdNtBookCourseWeek> bookCourseWeeksOne = new ArrayList<>();
                List<TdNtBookCourseWeek> bookCourseWeeksTwo = new ArrayList<>();
                int sizeone = 0;
                int sizetwo = 0;
                for (int i = 0; i < weeks.size(); i++) {//趟数
                    if (weeks.get(i).getWeek() > week) {
                        bookCourseWeeksOne.add(sizeone, weeks.get(i));
                        sizeone++;
                    } else {
                        bookCourseWeeksTwo.add(sizetwo, weeks.get(i));
                        sizetwo++;
                    }

                }
                bookCourseWeeksOne.addAll(bookCourseWeeksTwo);

                /**
                 * 更新课程表信息
                 */
                bookCourse.setState(2);
                bookCourse.setTea_id(tdNtBookCourseUpdate.getTea_id());
                bookCourse.setEceiving_time(new Timestamp(System.currentTimeMillis()));
                tdNtBookCourseDao.updateBook(bookCourse);
                /**
                 * 循环添加课程表  及预约信息
                 */
                int day = 0;
                int week_day = week;
                int number = 0;
                for (int i = 0; i < reserve_size; i++) {
                    TdNtBookCourseWeek tdNtBookCourseWeek = null;
                    if (i < bookCourseWeeksOne.size()) {
                        tdNtBookCourseWeek = bookCourseWeeksOne.get(i);
                    } else {
                        size = i / bookCourseWeeksOne.size();
                        tdNtBookCourseWeek = bookCourseWeeksOne.get(i - bookCourseWeeksOne.size() * size);

                    }
                    if (tdNtBookCourseWeek.getWeek() - week_day > 0) {
                        day = day + tdNtBookCourseWeek.getWeek() - week_day;
                        logger.info("day1=" + day);
                    } else if (tdNtBookCourseWeek.getWeek() - week_day == 0) {
                        if (size != number) {
                            day = day + 7;
                        }
                        logger.info("day2=" + day);
                    } else {
                        if (week_day == 7 && tdNtBookCourseWeek.getWeek() != 7) {
                            day = day + tdNtBookCourseWeek.getWeek();
                        } else {
                            day = day + tdNtBookCourseWeek.getWeek() - week_day + 7;
                        }
                        logger.info("day3=" + day);

                    }
                    number = size;
                    week_day = tdNtBookCourseWeek.getWeek();
                    if (number < 1) {
                        /**
                         * 更新课程表预约信息
                         */
                        tdNtBookCourseWeek.setStart_time(tdNtBookCourseUpdate.getWeeks().get(tdNtBookCourseWeek.getBook_cou_week_id()));
                        tdNtBookCourseDao.updateBookweek(tdNtBookCourseWeek);
                    }
                    logger.info("day=" + day);
                    logger.info("rectime=" + CommonUtil.getRerceveTime(tdNtBookCourseWeek.getStart_time(), day));

                    /**
                     * 添加预约信息
                     */
                    BigDecimal reserve_amount = tdNtMembSetmealDetail.getSet_amout().divide(
                            new BigDecimal(tdNtMembSetmealDetail.getSet_time()), 2, BigDecimal.ROUND_HALF_EVEN).multiply(new BigDecimal(60));
                    TdNtReserveInsert tdNtReserveInsert = new TdNtReserveInsert();
                    tdNtReserveInsert.setCou_id(bookCourse.getCou_id());
                    tdNtReserveInsert.setMemb_id(bookCourse.getMemb_id());
                    tdNtReserveInsert.setAmout(reserve_amount);
                    tdNtReserveInsert.setReserve_time(60);
                    tdNtReserveInsert.setTea_id(bookCourse.getTea_id());
                    tdNtReserveInsert.setReserve_start_time(CommonUtil.getRerceveTime(tdNtBookCourseWeek.getStart_time(), day));
                    tdNtReserveInsert.setReserve_end_time(CommonUtil.getRerceveTime(tdNtBookCourseWeek.getStart_time() + 1, day));
                    tdNtReserveInsert.setType(Constants.ReserveType.setmeal_course);
                    tdNtReserveDao.insertTdNtReserve(tdNtReserveInsert);
                    /**
                     * 添加课程表信息
                     */
                    TdNtBookCourseWeekHis tdNtBookCourseWeekHis = new TdNtBookCourseWeekHis();
                    tdNtBookCourseWeekHis.setBook_cou_id(tdNtBookCourseWeek.getBook_cou_id());
                    tdNtBookCourseWeekHis.setBook_cou_week_id(tdNtBookCourseWeek.getBook_cou_week_id());
                    tdNtBookCourseWeekHis.setDay_class_time(tdNtBookCourseWeek.getDay_class_time());
                    tdNtBookCourseWeekHis.setStart_time(tdNtBookCourseWeek.getStart_time());
                    tdNtBookCourseWeekHis.setWeek(tdNtBookCourseWeek.getWeek());
                    tdNtBookCourseWeekHis.setWeek_free_time(tdNtBookCourseWeek.getWeek_free_time());
                    tdNtBookCourseWeekHis.setReserve_id(tdNtReserveInsert.getReserve_id());
                    tdNtBookCourseWeekHis.setReserve_time(tdNtReserveInsert.getReserve_start_time());
                    tdNtBookCourseDao.insertBookCourseWeekHis(tdNtBookCourseWeekHis);
                }
                /**
                 * todo 给学生发接单推送及接单短信
                 */
                String content = "亲爱的外教君学员，老师已根据您的需求定制了您的学习计划。请在“我的课表”查看课程安排，并准时上课。祝您学习愉快！\n ";
                TdNtMemberTuisong tdNtMemberTuisong = tdNtMemberDao.findTdNtMemberTuisong(bookCourse.getMemb_id());
                if (tdNtMemberTuisong.getEqu_client_id() != null && !(tdNtMemberTuisong.getEqu_client_id().equals(Constants.default_equ_id))) {
                    /**
                     * 发推送
                     */
                    if (tdNtMemberTuisong.getEqu_type().equals("1")) {
                        AndroidReserveStudent.apnpush("外教君", content, tdNtMemberTuisong.getEqu_client_id(), tdNtBookCourseUpdate.getBook_cou_id());
                    } else {
                        logger.info(tdNtMemberTuisong.getEqu_client_id());
                        IosReserveStudent.apnpush("外教君", content, tdNtMemberTuisong.getEqu_client_id(), tdNtBookCourseUpdate.getBook_cou_id());
                    }
                }

                //发短信
                if (StringUtils.isNotBlank(tdNtMemberTuisong.getMemb_phone())) {
                    Sms sms = new Sms();
                    sms.setMemb_phone_area(tdNtMemberTuisong.getMemb_phone_area());
                    sms.setMemb_phone(tdNtMemberTuisong.getMemb_phone());

                    TwNtSendHisInsert twNtSendHis = new TwNtSendHisInsert();
                    twNtSendHis.setPhoneno(sms.getMemb_phone());
                    twNtSendHis.setSms_provider_id(110);
                    twNtSendHis.setYyyymmdd(CommonUtil.getMonth(new Date()));

                    if (SMSUtil.sendSms(sms, content)) {
                        twNtSendHis.setSms_type("Y");
                    } else {
                        twNtSendHis.setSms_type("N");
                    }
                    twNtSendHisDao.insertTwNtSendHis(twNtSendHis);
                }
                retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                retInfo.setTip("接单成功");
            } else {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip("Order taken");
            }

        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }
}
